package com.intelligentclass.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.intelligentclass.entity.Copy;
import com.intelligentclass.services.CopyService;
import com.intelligentclass.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/copy")
public class CopyController {

    @Autowired
    private CopyService copyService;

    // 创建一个文件收藏记录，guest为要收藏的收藏夹的原主的学号
    @PostMapping("/create")
    public ResponseEntity<?> createCopy(@RequestParam("guest") String guest,
                                        @RequestHeader("Authorization") String token) {
        try {
            // 去掉 "Bearer " 前缀
            token = token.replace("Bearer ", "");

            // 验证并解析 token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString(); // 提取用户名

            // 更新 token
            token = JWTUtil.updateToken(token);

            // 创建并保存文件收藏记录
            Copy copy = new Copy();
            copy.setCopyHost(username); // 使用 username 填入 host
            copy.setCopyGuest(guest);

            Copy savedCopy = copyService.saveCopy(copy);

            // 构造响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("savedCopy", savedCopy);
            response.put("updatedToken", token);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }

    // 获取所有收藏的文件
    @GetMapping("/all")
    public ResponseEntity<?> getAllCopies(@RequestHeader("Authorization") String token) {
        try {
            // 去掉 "Bearer " 前缀
            token = token.replace("Bearer ", "");

            // 验证并解析 token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString();

            // 获取所有文件收藏记录
            List<Copy> copies = copyService.findAllCopies();

            // 构建响应数据
            List<Map<String, Object>> response = copies.stream().map(copy -> {
                Map<String, Object> copyData = new HashMap<>();
                copyData.put("id", copy.getCopyId());
                copyData.put("host", copy.getCopyHost());
                copyData.put("guest", copy.getCopyGuest());
                return copyData;
            }).collect(Collectors.toList());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }

    // 删除收藏记录通过 guest 和 token
    @DeleteMapping("/delete")
    public ResponseEntity<?> deleteCopy(@RequestParam("guest") String guest,
                                        @RequestHeader("Authorization") String token) {
        try {
            // 去掉 "Bearer " 前缀
            token = token.replace("Bearer ", "");

            // 验证并解析 token
            DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
            String username = decodedJWT.getClaim("username").asString(); // 当前用户作为 host

            // 查找收藏记录
            Copy copy = copyService.findByHostAndGuest(username, guest);
            if (copy == null) {
                return ResponseEntity.status(404).body("Copy not found");
            }

            // 删除收藏记录
            copyService.deleteCopy(copy);

            // 返回成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("message", "Copy deleted successfully");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("Invalid or expired token");
        }
    }
}
